<template>
  <!-- 合同管理 -->
  <div class="wrapper">
    <search-form ref="searhForm" :area="'basic'" :display="'representative'" @search="search" :addType="1" @handleAdd="handleAdd" @handleDel="handleDel">
    </search-form>

    <a-card :body-style="{ padding: 0 }" :bordered="false">
      <a-spin :indicator="indicator" :spinning="spinning" tip="获取数据中...">
        <a-button type="primary" @click="openStart">
          批量生成账单
        </a-button>
        <div class="spin-content">
          <a-table size="small" bordered :rowKey="(record) => record.id" :columns="columns" :dataSource="tableList" :pagination="pagination" :rowSelection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }">
            <template slot="telTitle">
              <span>{{
                queryParam.personType == 1 ? "定位手机" : "手机"
              }}</span>
            </template>
            <span slot="status" slot-scope="text">
              <span v-if="queryParam.ReminderType == 1" class="circular red">
              </span>
              <span v-if="queryParam.ReminderType == 2" class="circular orange">
              </span>
            </span>
            <span slot="action" slot-scope="text, record">
              <template>
                <a size="small" type="link" @click="handleEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a size="small" type="link" @click="handleView(record)">查看</a>
                <a-popconfirm @confirm="contractAction(record)" placement="left" :title="record.contractState == null ? '确定终止合同？':'确定启用合同'" okText="确定" cancelText="取消">
                  <a-button type="link" style="margin-left: 14px">{{ record.contractState == null ? '终止' : '启用' }}</a-button>
                </a-popconfirm>
              </template>
            </span>
          </a-table>
        </div>
      </a-spin>
    </a-card>
    <info-modal :actionType="action" ref="infomodal" @save="handleSave"></info-modal>

    <search-modal ref="searchmodal" @save="start" />

    <a-modal title="终止合同" :width="400" :maskClosable="false" :visible="visibleContract" @cancel="visibleContract = false">
      <a slot="footer">
        <a-button @click="visibleContract = false">取消</a-button>
        <a-button @click="handleEndContract">确定</a-button>

      </a>
      <div>
        <a-form :form="form">
          <a-form-item v-bind="formItemLayout1" label="选择终止时间">
            <a-date-picker value-formate="YYYY-MM-DD" v-decorator="[
        'TrueEndDate',
        { rules: [{ required: true, message: '选择终止时间!' }] },
    ]">
            </a-date-picker>

          </a-form-item>

        </a-form>
      </div>

    </a-modal>
  </div>
</template>

<script>
import Vue from "vue";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { getContractByID, getContractList, saveContract, deleteContract, buildContractBills, SetContractState } from "@/api/allApi";

import searchModal from "./modules/searchModal.vue";
import SearchForm from "./modules/searchform";
import InfoModal from "./modules/infomodal";
import { tranDate } from "@/utils/util";

const userInfo = Vue.ls.get(ACCESS_TOKEN); // DepartmentID

export default {
  components: { SearchForm, InfoModal, searchModal },
  props: {
    display: {
      type: String,
      required: false,
      default: "default",
    },
  },
  async created () { },
  data () {
    return {
      form: this.$form.createForm(this),
      currentId: '',
      formItemLayout1: {
        labelCol: {
          xs: { span: 8 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 16 },
          sm: { span: 16 }
        }
      },
      action: "add",
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      spinning: false,
      queryParam: {
        index: 1,
        pageSize: 10,
      },
      visibleContract: false,
      addType: 1,
      selectedRowKeys: [],
      tableList: [],
      pagination: {
        onChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize);
        },
        current: 1,
        total: 0,
        showQuickJumper: true,
        size: "small",
        defaultPageSize: 10,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ["5", "10", "15", "20"],

        position: "bottom",
      },
      userInfoData: userInfo,
    };
  },
  watch: {},
  computed: {
    columns () {
      return [
        {
          title: "合同单号",
          dataIndex: "contractNO",
          key: "contractNO",
          align: "center",
        },
        {
          title: "联系人",
          dataIndex: "linkMan",
          key: "linkMan",
          align: "center",
        },
        {
          title: "联系电话",
          dataIndex: "linkManTel",
          key: "linkManTel",
          align: "center",
        },
        {
          title: "租期",
          dataIndex: "time",
          key: "time",
          align: "center",
        },
        {
          title: "合同月租金",
          dataIndex: "rent",
          key: "rent",
          align: "center",
        },

        {
          title: "操作",
          width: "150px",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
        },
      ];
    },
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.initData(this.queryParam);
  },
  methods: {
    async initData (params) {
      this.spinning = true;
      const { data, page } = await getContractList({
        ...params,
      });
      this.spinning = false;
      this.pagination.total = page.RecordCount;
      this.tableList = data;
      this.tableList.map((a) => {
        a.time = `${tranDate(a.startTime)} ~ ${tranDate(a.endTime)}`;
        a.IsReply = a.IsReply ? "是" : "否";
        a.isComplete = a.confirmUserID > 0 ? "是" : "否";
      });
    },
    search (data) {
      console.log(data);
      this.queryParam = { ...this.queryParam, ...data, contractstate: data.contractstate, index: 1 };
      this.pagination.current = 1;
      this.initData(this.queryParam);
    },

    handleAdd () {
      this.action = "add";

      this.$refs.infomodal.view();
    },

    contractAction (row) {
      console.log(row)
      let _this = this
      _this.currentId = row.id
      if (row.contractState == null) { // 终止合同
        _this.visibleContract = true;
        _this.form.resetFields();
      } else {
        SetContractState({ contractState: 1, ContractID: row.id }).then(res => {
          if (res.success) {
            _this.$message.success(res.message)
            _this.initData(_this.queryParam);
          }
        });
      }
    },

    handleEndContract () {
      let _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          SetContractState({ contractState: 0, ContractID: _this.currentId, ...values }).then(res => {
            if (res.success) {
              _this.$message.success(res.message)
              _this.visibleContract = false
              _this.initData(_this.queryParam);
            }
          });
        }
      });

    },

    handleEdit (data) {
      this.action = "edit";
      getContractByID({ id: data.id })
        .then((res) => {
          this.$refs.infomodal.view(res.data);
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    handleSave (values) {
      saveContract({ ...values }).then(res => {
        this.$refs.infomodal.close();

        this.initData(this.queryParam)
      })
    },
    /**
     * 查看详情
     * @param {*} data
     */
    handleView (data) {
      this.spinning = true;
      this.action = "view";
      getContractByID({ id: data.id })
        .then((res) => {
          this.$refs.infomodal.view(res.data);
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    openStart () {
      this.$refs.searchmodal.view();

    },

    start (p) {
      console.log(p)
      let _this = this
      buildContractBills(p).then(res => {
        if (res.data || res.success) {
          _this.$message.success(res.message)
          _this.$refs.searchmodal.closeModal();

        }
      })
    },


    /**
     * 批量删除
     */
    async handleDel () {
      this.spinning = true;
      const { code, message } = await deleteContract(this.selectedRowKeys);
      this.spinning = false;
      this.selectedRowKeys = [];
      this.initData(this.queryParam);

      this.$message.success(message);

    },

    /** 选择框 */
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },

    pageOnChange (index, pageSize) {
      this.spinning = true;
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index,
      });
      Object.assign(this.queryParam, {
        pageSize,
        index,
      });
      this.initData(this.queryParam);
    },
  },
};
</script>
<style lang="less">
.wrapper {
  /deep/ .ant-badge-status-dot {
    width: 14px;
    height: 14px;
  }
}

.tr-red {
  td {
    color: red;
  }
}

.circular {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
  &.red {
    background: red;
  }
  &.orange {
    background: orange;
  }
}
</style>
